package logic.handler;

import dao.ConcreteOperatorInter;
import io.http.HTTPHandler;
import io.json.JsonReader;
import io.json.JsonWritter;
import model.IdentifyBean;
import model.NumberBean;
import utils.XmlTools;

import javax.servlet.http.HttpServletResponse;

/**
 * 处理验证码请求的Handler
 * Created by jcala on 2016/3/16.
 */
public class IdentifyCodeHandler implements IdentifyCodeHandlerInter {
    private String data;
    private HttpServletResponse response;
    private ConcreteOperatorInter operator = null;

    public IdentifyCodeHandler(String data, HttpServletResponse response) {
        this();
        this.response = response;
        this.data = data;
    }

    private IdentifyCodeHandler() {
    }

    /**
     * 1 获取封装手机号信息的javabean
     * 2 生成验证码
     * 3 发送请求给验证码平台api并传入要发给客户端手机的随机数，将返回来的结果信息解析得到是否成功的布尔值
     * 4 如果成功就将要返回给客户端的IdentifyBean的状态码值设置为91，并传入要成的随机数
     * 5 将IdentifyBean转为json数据并通过HTTP返回给客户端
     */
    @Override
    public void handle() {
        NumberBean bean= JsonReader.readNumber(data);
        int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);
        boolean result = new XmlTools().identifyCodeStatus(HTTPHandler.setMsg(bean.getNumber(), mobile_code));
        IdentifyBean iden=new IdentifyBean();
        if (result) {
            iden.setCode(91);
            iden.setRandom(mobile_code);
        } else {
            iden.setCode(90);
        }
        HTTPHandler.sendMsgToHTTP(response, JsonWritter.WriteToIdentify(iden));
    }
}
